package com.matrix.async.core;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import com.matrix.async.service.AsyncTaskService;

public class ExceptionHandlerFactoryBean implements InitializingBean, FactoryBean<Object> {

	@Autowired
	private AsyncTaskService asyncTaskService;
	private ThreadFactory threadFactory = null;
	private int interval = 60 * 60 * 1000;
	private int overtime = 60 * 60;
	private int startupDelay = 0;
	ExceptionHandler thread = null;

	public ExceptionHandlerFactoryBean() {

	}

	@Override
	public void afterPropertiesSet() throws Exception {
		thread = new ExceptionHandler(asyncTaskService, threadFactory);
		if (interval > 0) {
			thread.setInterval(interval);
		}
		if (overtime > 0) {
			thread.setOvertime(overtime);
		}

		thread.setStartupDelay(startupDelay);
	}

	@Override
	public Object getObject() throws Exception {

		return thread;
	}

	@Override
	public Class<?> getObjectType() {

		return ExceptionHandler.class;
	}

	@Override
	public boolean isSingleton() {
		return false;
	}

	public void setInterval(int interval) {
		if (interval < 60) {
			throw new IllegalArgumentException("The paramenter 'interval' can't be less than 60 ");
		}
		this.interval = interval;
	}

	public void setOvertime(int overtime) {
		if (overtime < 60) {
			throw new IllegalArgumentException("The paramenter 'overtime' can't be less than 60 ");
		}
		this.overtime = overtime;
	}

	public void setStartupDelay(int startupDelay) {
		if (startupDelay < 0) {
			throw new IllegalArgumentException("The paramenter 'startupDelay' can't be less than 1 ");
		}
		this.startupDelay = startupDelay;
	}

}
